package com.rpcdemo.client.impl;

import com.alibaba.fastjson.JSON;
import com.rpcdemo.client.ProductClientService;
import com.rpcdemo.util.HeaderUtil;
import feign.hystrix.FallbackFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.util.Optional;

@Component
public class ProductClientServiceImpl implements FallbackFactory<ProductClientService> {

    private static final Logger logger = LoggerFactory.getLogger(ProductClientServiceImpl.class);

    @SuppressWarnings("rawtypes")
    private ResponseEntity logError(String appName, String apiUrl, Object header, Object parmas,
                                    Object body, Throwable cause) {

        logger.error("ask serverName:{}/{} header{} parmas{} RequestBody{} fallback!", appName,
                apiUrl, Optional.ofNullable(header).map(s -> JSON.toJSON(s)).orElse(""),
                Optional.ofNullable(parmas).map(s -> JSON.toJSON(s)).orElse(""),
                Optional.ofNullable(body).map(s -> JSON.toJSON(s)).orElse(""));

        logger.error("[异常信息]:", cause);
        // 调用其他服务错误, 一般是请求超时或其他
        return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("12", "2112")).build();
    }

    @Override
    @SuppressWarnings("unchecked")
    public ProductClientService create(Throwable throwable) {

        return new ProductClientService() {
            @Override
            public String queryProductByIds(String id) {
                return null;
            }
        };
    }
}
